import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
// import message from 'element-ui/packages/message'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url VUE_APP_URL
  // eslint-disable-next-line no-undef
  baseURL: VUE_APP_URL.baseUrl,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['satoken'] = getToken()
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const errmsg = res.message || 'Error'
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: errmsg,
        type: 'error',
        duration: 5 * 1000
      })
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('你是否要重新登录', '登出', {
          confirmButtonText: '登录',
          cancelButtonText: '退出',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.code === 500) {
        const message = res.message
        if (message.indexOf('token') >= 0) {
          MessageBox.confirm('你是否要重新登录', '登出', {
            confirmButtonText: '登录',
            cancelButtonText: '退出',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              router.push(`/login?redirect=${router.history.current.fullPath}`)
            })
          })
        }
      }
      return Promise.reject(new Error(errmsg))
    } else {
      return res
    }
  },
  error => {
    console.log({ error }) // for debug
    Message({
      message: '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
